package com.huicun.pay.utils;

import com.google.gson.Gson;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

/**
 * @Time: 2021/4/12 19:36
 * @Author: lidiwei
 */
public class HttpUtils {
    private static OkHttpClient okHttpClient;
    private static final Gson gson = new Gson();

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient();
        }
        return okHttpClient;
    }

    public static String postJson(String url, HashMap<String, Object> map) throws Exception {
        Request build = new Request.Builder()
                .post(RequestBody.create(gson.toJson(map), MediaType.get("application/json")))
                .url(url)
                .build();
        return Objects.requireNonNull(getOkHttpClient().newCall(build).execute().body()).string();
    }


    public static String get() {
        return "";
    }

    public static String postXml(String url, String xml) throws Exception {
        Request build = new Request.Builder()
                .post(RequestBody.create(xml, MediaType.get("application/xml")))
                .url(url)
                .build();
        return Objects.requireNonNull(getOkHttpClient().newCall(build).execute().body()).string();
    }

    public static <T> T postXml(String url, String xml, Class<T> c) throws Exception {
        Request build = new Request.Builder()
                .post(RequestBody.create(xml, MediaType.get("application/xml")))
                .url(url)
                .build();
        String string = Objects.requireNonNull(getOkHttpClient().newCall(build).execute().body()).string();
        if (!"".equals(string)) {
            return gson.fromJson(string, c);
        }
        return null;
    }
}
